<!--
  * 数据库管理工具
  *
  * @Author:    1024创新实验室-主任：卓大
  * @Date:      2024-01-01 00:00:00
  * @Wechat:    zhuda1024
  * @Email:     lab1024@163.com
  * @Copyright  1024创新实验室 （ https://1024lab.net ），Since 2012
-->
<template>
  <div class="database-manager">
    <a-layout style="height: 100vh; background: #f5f7fa;">
      <!-- 左侧数据源选择 -->
      <a-layout-sider 
        v-show="!leftSiderHidden"
        :width="leftSiderWidth" 
        class="datasource-sider"
        :collapsed="leftSiderCollapsed"
        :collapsible="true"
        @collapse="handleLeftSiderCollapse"
        :trigger="null"
      >
        <!-- 折叠时的内容 -->
        <template #trigger>
          <div class="sider-trigger" @click="toggleLeftSider">
            <MenuFoldOutlined v-if="!leftSiderCollapsed" />
            <MenuUnfoldOutlined v-else />
          </div>
        </template>
        
        <div class="sider-content">
          <div class="sider-header">
            <div class="header-title">
              <DatabaseOutlined class="header-icon" />
              <h3 v-show="!leftSiderCollapsed">数据源管理</h3>
            </div>
            <a-button 
              v-show="!leftSiderCollapsed"
              type="text" 
              size="small"
              class="refresh-btn"
              @click="handleRefreshDatasources"
            >
              <template #icon>
                <ReloadOutlined />
              </template>
            </a-button>
          </div>
          
          <div class="datasource-selector" v-show="!leftSiderCollapsed">
            <label class="selector-label">选择数据源</label>
          <a-select
            v-model:value="selectedDatasourceId"
            placeholder="请选择数据源"
              class="datasource-select"
            @change="handleDatasourceChange"
          >
            <a-select-option
              v-for="datasource in datasourceList"
              :key="datasource.id"
              :value="datasource.id"
            >
                <div class="datasource-option">
                  <DatabaseOutlined class="option-icon" />
                  <span>{{ datasource.name }}</span>
                </div>
            </a-select-option>
          </a-select>
          </div>

          <!-- 数据库对象树 -->
          <div v-if="selectedDatasourceId && !leftSiderCollapsed" class="object-tree-container">
            <label class="tree-label">数据库对象</label>
          <a-tree
            :tree-data="objectTreeData"
            :expanded-keys="expandedKeys"
              class="object-tree"
            @expand="onExpand"
            @select="onSelect"
          >
            <template #title="{ title, key, type }">
                <span class="tree-node">
                  <DatabaseOutlined v-if="type === 'database'" class="tree-icon database-icon" />
                  <TableOutlined v-else-if="type === 'table'" class="tree-icon table-icon" />
                  <EyeOutlined v-else-if="type === 'view'" class="tree-icon view-icon" />
                  <CodeOutlined v-else class="tree-icon" />
                  <span class="node-title">{{ title }}</span>
              </span>
            </template>
          </a-tree>
          </div>
          
          <!-- 折叠时显示的数据源快捷选择 -->
          <div v-if="leftSiderCollapsed" class="collapsed-datasource-list">
            <div class="collapsed-header">
              <DatabaseOutlined class="collapsed-icon" />
            </div>
            <div class="collapsed-datasources">
              <div 
                v-for="datasource in datasourceList.slice(0, 5)" 
                :key="datasource.id"
                class="collapsed-datasource-item"
                :class="{ 'active': selectedDatasourceId === datasource.id }"
                @click="handleDatasourceChange(datasource.id)"
                :title="datasource.name"
              >
                <DatabaseOutlined class="item-icon" />
              </div>
            </div>
            <div v-if="datasourceList.length > 5" class="collapsed-more">
              <a-tooltip title="更多数据源">
                <EllipsisOutlined />
              </a-tooltip>
            </div>
          </div>
        </div>
      </a-layout-sider>

      <!-- 右侧主要内容 -->
      <a-layout>
        <a-layout-content class="main-content">
          <div class="content-wrapper">
            <!-- SQL编辑器 - 固定显示 -->
            <div class="sql-editor-section">
              <div class="editor-header">
                                <div class="header-left">
                  <CodeOutlined class="header-icon" />
                <h3>SQL编辑器</h3>
                  <a-button 
                    type="text" 
                    size="small"
                    @click="toggleLeftSiderVisibility"
                    class="toggle-sider-btn"
                    :title="leftSiderHidden ? '显示数据源面板' : '隐藏数据源面板'"
                  >
                    <template #icon>
                      <MenuFoldOutlined v-if="!leftSiderHidden" />
                      <MenuUnfoldOutlined v-else />
                    </template>
                    {{ leftSiderHidden ? '显示面板' : '隐藏面板' }}
                  </a-button>
                </div>
                <div class="header-actions">
                  <a-button 
                    size="small" 
                    @click="handleClearSql"
                    class="action-btn"
                  >
                    <DeleteOutlined />
                    清空
                  </a-button>
                  <a-button 
                    size="small" 
                    @click="handleFormatSql"
                    class="action-btn"
                  >
                    <FormOutlined />
                    格式化
                  </a-button>
                  <a-button 
                    type="primary" 
                    size="small"
                    @click="handleExecuteSql" 
                    :loading="executing"
                    class="execute-btn"
                  >
                    <PlayCircleOutlined />
                    执行 (F5)
                  </a-button>
                  <a-button 
                    type="primary" 
                    size="small"
                    @click="handleExecuteMultipleSql" 
                    :loading="executingMultiple"
                    :disabled="!hasMultipleStatements"
                    class="execute-multiple-btn"
                  >
                    <PlayCircleOutlined />
                    批量执行
                  </a-button>
                </div>
              </div>
              
              <div class="editor-container">
                <div class="sql-editor-wrapper">
                  <MonacoEditor
                    v-model="sqlContent"
                    language="sql"
                    :theme="'vs'"
                    :font-size="sqlFontSize"
                    :read-only="executing || executingMultiple"
                    :auto-height="true"
                    :min-height="180"
                    :max-height="400"
                    @select="handleMonacoSelect"
                    @change="handleMonacoChange"
                  ></MonacoEditor>
                </div>
              </div>
            </div>

            <!-- 可折叠的其他模块 -->
            <div class="collapsible-sections">
            <!-- 查询结果 -->
              <a-collapse v-model:activeKey="activeCollapseKeys" ghost class="custom-collapse">
                <a-collapse-panel key="result" header="查询结果" :collapsible="'header'" class="result-panel">
                  <template #header>
                    <div class="panel-header">
                      <BarChartOutlined class="panel-icon" />
                      <span>查询结果</span>
                    </div>
                  </template>
            <div class="result-section" v-if="queryResult">
              <div class="result-header">
                <h3>查询结果</h3>
                <a-space>
                  <span v-if="queryResult.executionTime">
                          执行时间: {{ formatExecutionTime(queryResult.executionTime) }}
                  </span>
                  <span v-if="queryResult.total">
                    总行数: {{ queryResult.total }}
                  </span>
                  <span v-if="queryResult.affectedRows">
                    影响行数: {{ queryResult.affectedRows }}
                  </span>
                        <span v-if="queryResult.warning">
                          <a-tag color="orange">{{ queryResult.warning }}</a-tag>
                        </span>
                        <a-button @click="handleExportResult" :disabled="!canExport">导出</a-button>
                </a-space>
              </div>

              <!-- 错误信息 -->
              <div v-if="!queryResult.success" class="error-message">
                <a-alert
                  :message="queryResult.errorMessage"
                  type="error"
                  show-icon
                />
              </div>

              <!-- 结果表格 -->
              <div v-else-if="queryResult.columns && queryResult.columns.length > 0" class="result-table">
                <a-table
                  :columns="resultColumns"
                  :data-source="queryResult.rows"
                        :scroll="{ x: true, y: resultTableHeight }"
                  size="small"
                        :pagination="tablePagination"
                        @change="handleTableChange"
                        :loading="tableLoading"
                        :row-key="(record, index) => `row-${index}`"
                        :sticky="{ offsetHeader: 0 }"
                        ref="resultTableRef"
                      >
                        <template #bodyCell="{ column, record, index }">
                          <template v-if="column.dataIndex && column.dataIndex !== 'rowIndex'">
                            <span v-if="record[column.dataIndex] === null || record[column.dataIndex] === undefined" style="color: #999;">
                              NULL
                            </span>
                            <a-tooltip v-else-if="typeof record[column.dataIndex] === 'string' && record[column.dataIndex].length > 100" :title="record[column.dataIndex]">
                              <span>{{ record[column.dataIndex].substring(0, 100) }}...</span>
                            </a-tooltip>
                            <span v-else>{{ record[column.dataIndex] }}</span>
                          </template>
                        </template>
                      </a-table>
              </div>

              <!-- 成功消息 -->
              <div v-else class="success-message">
                <a-alert
                  :message="`SQL执行成功，影响 ${queryResult.affectedRows || 0} 行数据`"
                  type="success"
                  show-icon
                />
              </div>
            </div>
                </a-collapse-panel>

            <!-- 查询历史 -->
                <a-collapse-panel key="history" header="查询历史" :collapsible="'header'" class="history-panel">
                  <template #header>
                    <div class="panel-header">
                      <HistoryOutlined class="panel-icon" />
                      <span>查询历史</span>
                    </div>
                  </template>
            <div class="history-section">
              <div class="history-header">
                <h3>查询历史</h3>
                      <a-space>
                        <a-input-search
                          v-model:value="historySearchKeyword"
                          placeholder="搜索SQL内容、数据源名称或用户"
                          style="width: 300px"
                          @search="handleSearchHistory"
                          @change="handleSearchHistory"
                        />
                <a-button @click="handleClearHistory">清空历史</a-button>
                      </a-space>
              </div>
              
                    <a-table
                      :columns="historyColumns"
                :data-source="queryHistory"
                      :pagination="historyPagination"
                size="small"
                      :loading="historyLoading"
                      :row-key="(record) => record.id"
                      :scroll="{ y: historyTableHeight }"
                    >
                      <template #bodyCell="{ column, record }">
                        <template v-if="column.dataIndex === 'sqlContent'">
                          <a-tooltip :title="record.sqlContent">
                            <span class="sql-content">{{ record.sqlContent }}</span>
                          </a-tooltip>
                        </template>
                        <template v-else-if="column.dataIndex === 'status'">
                          <a-tag :color="record.status === 1 ? 'green' : 'red'">
                            {{ record.statusDesc }}
                        </a-tag>
                </template>
                        <template v-else-if="column.dataIndex === 'executionTime'">
                          <span>{{ record.formattedExecutionTime }}</span>
                        </template>
                        <template v-else-if="column.dataIndex === 'createTime'">
                          <span>{{ record.formattedCreateTime }}</span>
                        </template>
                        <template v-else-if="column.dataIndex === 'action'">
                          <a-button type="link" size="small" @click="handleReuseSql(record)">
                            重用
                          </a-button>
                        </template>
                      </template>
                    </a-table>
                  </div>
                </a-collapse-panel>
              </a-collapse>
            </div>
          </div>
        </a-layout-content>
      </a-layout>
    </a-layout>

    <!-- 布局控制面板 -->
    <div 
      v-if="layoutControlsVisible" 
      class="layout-controls"
      :style="{ left: controlPanelPosition.x + 'px', top: controlPanelPosition.y + 'px' }"
      @mousedown="startDrag"
    >
      <a-card 
        title="布局控制" 
        size="small" 
        class="control-card"
        :body-style="{ padding: '16px' }"
      >
        <template #title>
          <div class="card-title">
            <SettingOutlined class="title-icon" />
            <span>布局控制</span>
          </div>
        </template>
        <template #extra>
          <a-space>
            <a-button size="small" type="text" @click="resetLayout" class="control-btn">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
            <a-button size="small" type="text" @click="toggleLayoutControls" class="control-btn">
              <template #icon>
                <CloseOutlined />
              </template>
              隐藏
            </a-button>
          </a-space>
        </template>
        
        <a-space direction="vertical" style="width: 100%;">
          <!-- 布局控制 -->
          <a-divider orientation="left">布局设置</a-divider>
          <div>
            <label>左侧面板显示状态</label>
            <a-space style="width: 100%; margin-top: 8px;">
              <a-button 
                size="small" 
                :type="!leftSiderHidden ? 'primary' : 'default'"
                @click="leftSiderHidden = false"
              >
                显示
              </a-button>
              <a-button 
                size="small" 
                :type="leftSiderHidden ? 'primary' : 'default'"
                @click="leftSiderHidden = true"
              >
                隐藏
              </a-button>
            </a-space>
          </div>
          <div v-if="!leftSiderHidden">
            <label>左侧面板宽度: {{ leftSiderWidth }}px</label>
            <a-slider
              v-model:value="leftSiderWidth"
              :min="200"
              :max="500"
              :step="10"
              style="width: 100%;"
            />
          </div>
          <div>
            <label>SQL编辑器行数: {{ sqlEditorRows }}行</label>
            <a-slider
              v-model:value="sqlEditorRows"
              :min="5"
              :max="20"
              :step="1"
              style="width: 100%;"
            />
          </div>
          <div>
            <label>结果表格高度: {{ resultTableHeight }}px</label>
            <a-slider
              v-model:value="resultTableHeight"
              :min="200"
              :max="600"
              :step="50"
              style="width: 100%;"
            />
          </div>
          <div>
            <label>历史表格高度: {{ historyTableHeight }}px</label>
            <a-slider
              v-model:value="historyTableHeight"
              :min="200"
              :max="600"
              :step="50"
              style="width: 100%;"
            />
          </div>
          
          <!-- 字体设置 -->
          <a-divider orientation="left">字体设置</a-divider>
          <div>
            <label>SQL编辑器字体大小: {{ sqlFontSize }}px</label>
            <a-slider
              v-model:value="sqlFontSize"
              :min="12"
              :max="24"
              :step="1"
              style="width: 100%;"
            />
          </div>
          <div>
            <label>行号字体大小: {{ lineNumberFontSize }}px</label>
            <a-slider
              v-model:value="lineNumberFontSize"
              :min="10"
              :max="20"
              :step="1"
              style="width: 100%;"
            />
          </div>
          
          <!-- 查询设置 -->
          <a-divider orientation="left">查询设置</a-divider>
          <div>
            <label>分页大小: {{ pageSize }}条</label>
            <a-select v-model:value="pageSize" style="width: 100%; margin-top: 4px;">
              <a-select-option :value="10">10条</a-select-option>
              <a-select-option :value="20">20条</a-select-option>
              <a-select-option :value="50">50条</a-select-option>
              <a-select-option :value="100">100条</a-select-option>
              <a-select-option :value="200">200条</a-select-option>
              <a-select-option :value="500">500条</a-select-option>
            </a-select>
          </div>
          <div>
            <label>最大返回行数: {{ maxRows }}行</label>
            <a-slider
              v-model:value="maxRows"
              :min="100"
              :max="10000"
              :step="100"
              style="width: 100%;"
            />
          </div>
          <div>
            <label>超时时间: {{ timeout }}秒</label>
            <a-slider
              v-model:value="timeout"
              :min="5"
              :max="300"
              :step="5"
              style="width: 100%;"
            />
          </div>
        </a-space>
      </a-card>
    </div>

    <!-- 显示控制面板按钮 -->
    <div 
      v-if="!layoutControlsVisible" 
      class="show-controls-btn"
      :style="{ left: controlButtonPosition.x + 'px', top: controlButtonPosition.y + 'px' }"
      @mousedown="startDragButton"
    >
      <a-button 
        type="primary" 
        shape="circle" 
        size="large"
        @click="handleLayoutButtonClick"
        style="cursor: move;"
      >
        <template #icon>
          <SettingOutlined />
        </template>
      </a-button>
    </div>

    <!-- 性能监控按钮 -->
    <div 
      v-if="showPerformanceMonitor" 
      class="performance-monitor-btn"
      :style="{ left: performanceButtonPosition.x + 'px', top: performanceButtonPosition.y + 'px' }"
      @mousedown="startDragPerformanceButton"
    >
      <a-button 
        type="primary" 
        shape="circle" 
        size="large"
        @click="handlePerformanceButtonClick"
        style="cursor: move; background: #52c41a; border-color: #52c41a;"
      >
        <template #icon>
          <DashboardOutlined />
        </template>
      </a-button>
    </div>

    <!-- 显示左侧面板的浮动按钮 -->
    <div 
      v-if="leftSiderHidden" 
      class="show-sider-btn"
      :style="{ left: '20px', top: '50%', transform: 'translateY(-50%)' }"
    >
      <a-button 
        type="primary" 
        shape="circle" 
        size="large"
        @click="toggleLeftSiderVisibility"
        style="cursor: pointer; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-color: #667eea;"
      >
        <template #icon>
          <MenuUnfoldOutlined />
        </template>
      </a-button>
    </div>

    <!-- 性能监控弹窗 -->
    <a-modal
      v-model:open="showPerformanceModal"
      title="性能监控"
      width="600px"
      :footer="null"
      :destroyOnClose="true"
    >
      <PerformanceMonitor
        v-if="showPerformanceModal && queryResult"
        :execution-time="queryResult.executionTime || 0"
        :data-rows="queryResult.rows?.length || 0"
        :sql="(selectedText.value || '').trim() || sqlContent"
        @warning="handlePerformanceWarning"
        @suggestion="handlePerformanceSuggestion"
      />
    </a-modal>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted, computed, onUnmounted, h, watch, nextTick } from 'vue';
  import { message, Modal, Progress } from 'ant-design-vue';
  import {
    ReloadOutlined,
    DatabaseOutlined,
    TableOutlined,
    EyeOutlined,
    CodeOutlined,
    SettingOutlined,
    DashboardOutlined,
    DeleteOutlined,
    FormOutlined,
    PlayCircleOutlined,
    BarChartOutlined,
    HistoryOutlined,
    CloseOutlined,
    MenuFoldOutlined,
    MenuUnfoldOutlined,
    EllipsisOutlined,
  } from '@ant-design/icons-vue';
  import { datasourceApi } from '/@/api/business/datasource/datasource-api';
  import { databaseManagerApi } from '/@/api/business/datasource/database-manager-api';
  import PerformanceMonitor from './components/performance-monitor.vue';
  import { QUERY_CONFIG, UTILS, ERROR_MESSAGES } from './database-manager-config';
  import MonacoEditor from './components/monaco-editor.vue';

  // 数据源列表
  const datasourceList = ref([]);
  const selectedDatasourceId = ref(null);

  // 数据库对象树
  const objectTreeData = ref([]);
  const expandedKeys = ref([]);

  // SQL编辑器
  const sqlContent = ref('');
  const executing = ref(false);
  const executingMultiple = ref(false);
  // const sqlTextareaRef = ref(null); // 已移除，使用MonacoEditor
  // const codeEditorRef = ref(null); // 暂时移除代码编辑器引用
  // const lineNumbers = ref([1]); // 已移除，MonacoEditor自带行号
  
  // SQL语法高亮和选中相关
  // const selectedLines = ref([]); // 已移除，MonacoEditor自带选区处理
  const selectedText = ref('');
  // const selectionStart = ref(0); // 已移除，MonacoEditor自带选区处理
  // const selectionEnd = ref(0); // 已移除，MonacoEditor自带选区处理

  // 查询设置
  const pageSize = ref(50);
  const maxRows = ref(1000);
  const timeout = ref(30);
  const currentPage = ref(1);
  const tableLoading = ref(false);

  // 查询结果
  const queryResult = ref(null);

  // 查询历史
  const queryHistory = ref([]);

  // 性能监控
  const showPerformanceMonitor = ref(false);
  const performanceWarnings = ref([]);
  const performanceSuggestions = ref([]);

  // 历史搜索关键词
  const historySearchKeyword = ref('');
  const historyLoading = ref(false);

  // 布局控制相关
  const leftSiderWidth = ref(300);
  const leftSiderCollapsed = ref(false);
  const leftSiderHidden = ref(false);
  const sqlEditorRows = ref(8);
  const resultTableHeight = ref(400);
  const historyTableHeight = ref(400);
  const activeCollapseKeys = ref([]); // 默认折叠所有面板
  const layoutControlsVisible = ref(false);
  
  // 字体大小控制
  const sqlFontSize = ref(16);
  const lineNumberFontSize = ref(14);
  
  // 拖拽控制相关
  const controlPanelPosition = ref({ x: window.innerWidth - 340, y: 20 });
  const controlButtonPosition = ref({ x: window.innerWidth - 80, y: 20 });
  const isDragging = ref(false);
  const isDraggingButton = ref(false);
  const dragOffset = ref({ x: 0, y: 0 });
  
  // 性能监控相关
  const showPerformanceModal = ref(false);
  const performanceButtonPosition = ref({ x: window.innerWidth - 140, y: 20 });
  const isDraggingPerformanceButton = ref(false);

  // 历史表格列
  const historyColumns = ref([
    {
      title: 'SQL内容',
      dataIndex: 'sqlContent',
      key: 'sqlContent',
      width: 300,
      ellipsis: true,
    },
    {
      title: '数据源',
      dataIndex: 'datasourceName',
      key: 'datasourceName',
      width: 100,
    },
    {
      title: '执行时间',
      dataIndex: 'executionTime',
      key: 'executionTime',
      width: 80,
    },
    {
      title: '影响行数',
      dataIndex: 'rowCount',
      key: 'rowCount',
      width: 80,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 80,
    },
  ]);

  // 历史表格分页
  const historyPagination = computed(() => {
    return {
      current: 1,
      pageSize: 50,
      total: queryHistory.value.length,
      showSizeChanger: false,
      showQuickJumper: false,
      showTotal: (total, range) => `共 ${total} 条记录`,
      pageSizeOptions: ['50'],
    };
  });

  // 计算属性
  const isQueryMode = computed(() => {
    return sqlContent.value.toLowerCase().trim().startsWith('select');
  });

  // 检查是否有多个SQL语句
  const hasMultipleStatements = computed(() => {
    const sql = sqlContent.value.trim();
    if (!sql) return false;
    
    // 分割SQL语句（按分号分割，但忽略字符串中的分号）
    const statements = splitSqlStatements(sql);
    return statements.length > 1;
  });

  const canExport = computed(() => {
    return queryResult.value?.success && 
           queryResult.value?.rows && 
           queryResult.value.rows.length > 0 &&
           queryResult.value.rows.length <= QUERY_CONFIG.MAX_ROWS;
  });

  const tablePagination = computed(() => {
    if (!queryResult.value?.success || !isQueryMode.value) {
      return false;
    }
    
    return {
      current: currentPage.value,
      pageSize: pageSize.value, // 使用查询设置中的分页大小
      total: queryResult.value.total || 0,
      showSizeChanger: false, // 禁用表格的分页大小选择器，统一由布局控制面板管理
      showQuickJumper: true,
      showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
      pageSizeOptions: [pageSize.value.toString()], // 只显示当前设置的分页大小
    };
  });

  // 列宽状态管理
  const columnWidths = ref({});

  // 结果表格列
  const resultColumns = computed(() => {
    if (!queryResult.value?.columns) return [];
    
    // 添加行号列
    const columns = [
      {
        title: '#',
        dataIndex: 'rowIndex',
        key: 'rowIndex',
        width: 40, // 固定行号列宽度为40px
        fixed: 'left',
        customRender: ({ index }) => {
          const startIndex = (currentPage.value - 1) * pageSize.value;
          return h('span', { style: { color: '#666', fontWeight: 'bold' } }, startIndex + index + 1);
        },
      }
    ];
    
    // 添加数据列
    const dataColumns = queryResult.value.columns.map(col => {
      const columnKey = col.name;
      // 根据列标题计算自适应宽度
      const title = col.label || col.name;
      const titleWidth = title.length * 12 + 20; // 每个字符12px + 20px边距
      const defaultWidth = Math.max(80, Math.min(titleWidth, 200)); // 最小80px，最大200px
      const currentWidth = columnWidths.value[columnKey] || defaultWidth;
      
      return {
      title: col.label || col.name,
      dataIndex: col.name,
      key: col.name,
        width: currentWidth,
      ellipsis: true,
        customRender: ({ text }) => {
          if (text === null || text === undefined) {
            return h('span', { style: { color: '#999' } }, 'NULL');
          }
          if (typeof text === 'string' && text.length > 100) {
            return h('a-tooltip', { title: text }, [
              h('span', text.substring(0, 100) + '...')
            ]);
          }
          return text;
        },
      };
    });
    
    return [...columns, ...dataColumns];
  });

  // 获取数据源列表
  const getDatasourceList = async () => {
    try {
      const res = await datasourceApi.queryPage({ pageNum: 1, pageSize: 100 });
      datasourceList.value = res.data.records;
    } catch (error) {
      message.error('获取数据源列表失败');
    }
  };

  // 数据源变化处理
  const handleDatasourceChange = async (datasourceId) => {
    if (datasourceId) {
      await loadDatabaseObjects(datasourceId);
      await loadQueryHistory(); // 加载查询历史
    } else {
      objectTreeData.value = [];
      queryHistory.value = []; // 清空查询历史
    }
  };

  // 加载数据库对象
  const loadDatabaseObjects = async (datasourceId) => {
    try {
      const [tablesRes, viewsRes] = await Promise.all([
        databaseManagerApi.getDatabaseObjects(datasourceId, 'table'),
        databaseManagerApi.getDatabaseObjects(datasourceId, 'view'),
      ]);

      const treeData = [
        {
          title: '表',
          key: 'tables',
          type: 'database',
          children: tablesRes.data.map(table => ({
            title: table.objectName,
            key: `table_${table.objectName}`,
            type: 'table',
            objectName: table.objectName,
          })),
        },
        {
          title: '视图',
          key: 'views',
          type: 'database',
          children: viewsRes.data.map(view => ({
            title: view.objectName,
            key: `view_${view.objectName}`,
            objectName: view.objectName,
          })),
        },
      ];

      objectTreeData.value = treeData;
      expandedKeys.value = ['tables', 'views'];
    } catch (error) {
      message.error('加载数据库对象失败');
    }
  };

  // 树节点展开
  const onExpand = (keys) => {
    expandedKeys.value = keys;
  };

  // 树节点选择
  const onSelect = (selectedKeys, info) => {
    const node = info.node;
    if (node.type === 'table' || node.type === 'view') {
      // 生成安全的查询语句，使用当前设置的分页大小
      sqlContent.value = `SELECT * FROM ${node.objectName} LIMIT ${pageSize.value}`;
      currentPage.value = 1;
    }
  };

  // 刷新数据源
  const handleRefreshDatasources = () => {
    getDatasourceList();
  };

  // 清空SQL
  const handleClearSql = () => {
    sqlContent.value = '';
    queryResult.value = null;
  };

  // 格式化SQL
  const handleFormatSql = () => {
    // TODO: 实现SQL格式化
    message.info('SQL格式化功能开发中');
  };

  // 分割SQL语句的工具函数
  const splitSqlStatements = (sql) => {
    const statements = [];
    let currentStatement = '';
    let inString = false;
    let stringChar = '';
    let i = 0;
    
    while (i < sql.length) {
      const char = sql[i];
      
      // 处理字符串
      if ((char === "'" || char === '"') && (i === 0 || sql[i - 1] !== '\\')) {
        if (!inString) {
          inString = true;
          stringChar = char;
        } else if (char === stringChar) {
          inString = false;
        }
      }
      
      // 处理分号（不在字符串内）
      if (char === ';' && !inString) {
        const trimmed = currentStatement.trim();
        if (trimmed) {
          statements.push(trimmed);
        }
        currentStatement = '';
      } else {
        currentStatement += char;
      }
      
      i++;
    }
    
    // 添加最后一个语句（如果没有分号结尾）
    const trimmed = currentStatement.trim();
    if (trimmed) {
      statements.push(trimmed);
    }
    
    return statements;
  };

  // 执行SQL
  const handleExecuteSql = async () => {
    if (!selectedDatasourceId.value) {
      message.warning('请先选择数据源');
      return;
    }

    if (!sqlContent.value.trim()) {
      message.warning('请输入SQL语句');
      return;
    }

    // 检查SQL安全性
    const sql = sqlContent.value.trim().toLowerCase();
    if (sql.includes('drop') || sql.includes('delete') || sql.includes('truncate')) {
      Modal.confirm({
        title: '危险操作警告',
        content: '您即将执行一个可能影响数据的操作，确定要继续吗？',
        okText: '确定',
        cancelText: '取消',
        onOk: () => executeSqlInternal(),
      });
    } else {
      executeSqlInternal();
    }
  };

  // 内部执行SQL方法
  const executeSqlInternal = async () => {
    try {
      executing.value = true;
      tableLoading.value = true;
      showPerformanceMonitor.value = false;
      performanceWarnings.value = [];
      performanceSuggestions.value = [];
      
      // 获取要执行的SQL - 优先使用选中的文本，否则使用全部内容
      let sqlToExecute = selectedText.value.trim();
      if (!sqlToExecute) {
        sqlToExecute = sqlContent.value.trim();
      }
      
      if (!sqlToExecute) {
        message.warning('请先输入SQL语句或选中要执行的SQL');
        return;
      }
      
      const isQuery = sqlToExecute.toLowerCase().startsWith('select');

      // 检查SQL安全性
      if (UTILS.isDangerousSQL(sqlToExecute)) {
        message.warning('检测到危险操作，请谨慎执行');
      }

      // 检查查询范围
      if (isQuery && !sqlToExecute.toLowerCase().includes('limit') && !sqlToExecute.toLowerCase().includes('where')) {
        message.warning('建议添加WHERE条件或LIMIT子句以提高查询性能');
      }

      // 构建执行参数 - 每次都使用查询设置的分页参数
      const params = {
        datasourceId: selectedDatasourceId.value,
        sql: sqlToExecute,
        enablePagination: isQuery,
        pageNum: currentPage.value,
        pageSize: pageSize.value, // 始终使用设置的分页大小
        maxRows: maxRows.value,   // 始终使用设置的最大行数
        timeout: timeout.value,
      };

      const startTime = Date.now();
      const res = isQuery 
        ? await databaseManagerApi.executeQuery(params)
        : await databaseManagerApi.executeUpdate(params);
      const endTime = Date.now();

      queryResult.value = res.data;
      queryResult.value.executionTime = endTime - startTime;
      
      // 检查数据量警告
      if (res.data.success && isQuery && res.data.rows && res.data.rows.length >= maxRows.value) {
        queryResult.value.warning = `查询结果已达到最大行数限制(${maxRows.value}行)，建议添加WHERE条件或LIMIT子句`;
      }

      // 检查执行时间
      if (queryResult.value.executionTime > 5000) {
        queryResult.value.warning = `查询执行时间较长(${formatExecutionTime(queryResult.value.executionTime)})，建议优化查询条件`;
      }
      
      // 显示性能监控
      if (isQuery && res.data.success) {
        showPerformanceMonitor.value = true;
      }
      
      // 显示执行的SQL信息
      if (selectedText.value.trim()) {
        message.success(`已执行选中的SQL语句`);
      }
      
      // 重新加载查询历史
      await loadQueryHistory();

      if (res.data.success) {
        message.success('SQL执行成功');
      }
    } catch (error) {
      message.error('SQL执行失败');
      queryResult.value = {
        success: false,
        errorMessage: error.data?.msg || ERROR_MESSAGES.CONNECTION_FAILED,
      };
    } finally {
      executing.value = false;
      tableLoading.value = false;
    }
  };

  // 顺序执行多个SQL语句
  const handleExecuteMultipleSql = async () => {
    if (!selectedDatasourceId.value) {
      message.warning('请先选择数据源');
      return;
    }

    const sql = sqlContent.value.trim();
    if (!sql) {
      message.warning('请输入SQL语句');
      return;
    }

    // 分割SQL语句
    const statements = splitSqlStatements(sql);
    if (statements.length <= 1) {
      message.warning('请确保SQL语句包含多个以分号分隔的语句');
      return;
    }

    // 检查是否有危险操作
    const hasDangerousSql = statements.some(stmt => {
      const lowerStmt = stmt.toLowerCase();
      return lowerStmt.includes('drop') || lowerStmt.includes('delete') || lowerStmt.includes('truncate');
    });

    if (hasDangerousSql) {
      Modal.confirm({
        title: '危险操作警告',
        content: `检测到 ${statements.length} 条SQL语句中包含危险操作，确定要按顺序执行吗？`,
        okText: '确定执行',
        cancelText: '取消',
        onOk: () => executeMultipleSqlInternal(statements),
      });
    } else {
      executeMultipleSqlInternal(statements);
    }
  };

  // 内部顺序执行多个SQL语句
  const executeMultipleSqlInternal = async (statements) => {
    try {
      executingMultiple.value = true;
      tableLoading.value = true;
      showPerformanceMonitor.value = false;
      performanceWarnings.value = [];
      performanceSuggestions.value = [];

      const results = [];
      let totalExecutionTime = 0;
      let successCount = 0;
      let errorCount = 0;

      // 显示执行进度
      const progressModal = Modal.info({
        title: '批量执行SQL语句',
        content: h('div', [
          h('p', `共 ${statements.length} 条SQL语句，正在执行中...`),
          h('div', { style: 'margin: 16px 0;' }, [
            h('a-progress', {
              percent: 0,
              status: 'active',
              ref: 'progressRef'
            })
          ])
        ]),
        okButtonProps: { style: { display: 'none' } },
        cancelButtonProps: { style: { display: 'none' } },
        closable: false,
      });

      // 逐条执行SQL语句
      for (let i = 0; i < statements.length; i++) {
        const statement = statements[i].trim();
        if (!statement) continue;

        try {
          // 更新进度
          const progress = Math.round(((i + 1) / statements.length) * 100);
          progressModal.update({
            content: h('div', [
              h('p', `正在执行第 ${i + 1}/${statements.length} 条SQL语句`),
              h('div', { style: 'margin: 8px 0; font-family: monospace; font-size: 12px; color: #666;' }, 
                statement.length > 50 ? statement.substring(0, 50) + '...' : statement
              ),
              h('div', { style: 'margin: 16px 0;' }, [
                h('a-progress', {
                  percent: progress,
                  status: 'active'
                })
              ])
            ])
          });

          const isQuery = statement.toLowerCase().startsWith('select');
          
          // 构建执行参数
          const params = {
            datasourceId: selectedDatasourceId.value,
            sql: statement,
            enablePagination: isQuery,
            pageNum: 1, // 顺序执行时使用第一页
            pageSize: pageSize.value,
            maxRows: maxRows.value,
            timeout: timeout.value,
          };

          const startTime = Date.now();
          const res = isQuery 
            ? await databaseManagerApi.executeQuery(params)
            : await databaseManagerApi.executeUpdate(params);
          const endTime = Date.now();

          const executionTime = endTime - startTime;
          totalExecutionTime += executionTime;

          const result = {
            statement: statement,
            success: res.data.success,
            executionTime: executionTime,
            errorMessage: res.data.errorMessage,
            affectedRows: res.data.affectedRows,
            rows: res.data.rows,
            total: res.data.total,
          };

          results.push(result);

          if (res.data.success) {
            successCount++;
          } else {
            errorCount++;
          }

          // 如果执行失败，可以选择是否继续
          if (!res.data.success) {
            const continueResult = await new Promise((resolve) => {
              Modal.confirm({
                title: 'SQL执行失败',
                content: h('div', [
                  h('p', `第 ${i + 1} 条SQL语句执行失败:`),
                  h('p', { style: 'color: red;' }, res.data.errorMessage),
                  h('p', '是否继续执行剩余的SQL语句？')
                ]),
                okText: '继续执行',
                cancelText: '停止执行',
                onOk: () => resolve(true),
                onCancel: () => resolve(false),
              });
            });

            if (!continueResult) {
              break;
            }
          }

        } catch (error) {
          errorCount++;
          results.push({
            statement: statement,
            success: false,
            executionTime: 0,
            errorMessage: error.data?.msg || '执行失败',
          });

          const continueResult = await new Promise((resolve) => {
            Modal.confirm({
              title: 'SQL执行异常',
              content: h('div', [
                h('p', `第 ${i + 1} 条SQL语句执行异常:`),
                h('p', { style: 'color: red;' }, error.data?.msg || '执行失败'),
                h('p', '是否继续执行剩余的SQL语句？')
              ]),
              okText: '继续执行',
              cancelText: '停止执行',
              onOk: () => resolve(true),
              onCancel: () => resolve(false),
            });
          });

          if (!continueResult) {
            break;
          }
        }
      }

      // 关闭进度弹窗
      progressModal.destroy();

      // 显示执行结果
      const resultMessage = `批量执行完成！成功: ${successCount} 条，失败: ${errorCount} 条，总耗时: ${formatExecutionTime(totalExecutionTime)}`;
      
      if (errorCount === 0) {
        message.success(resultMessage);
      } else if (successCount === 0) {
        message.error(resultMessage);
      } else {
        message.warning(resultMessage);
      }

      // 显示详细结果
      Modal.info({
        title: '批量执行结果详情',
        width: 800,
        content: h('div', [
          h('div', { style: 'margin-bottom: 16px;' }, [
            h('p', { style: 'font-weight: bold;' }, resultMessage),
          ]),
          h('div', { style: 'max-height: 400px; overflow-y: auto;' }, [
            ...results.map((result, index) => 
              h('div', { 
                key: index,
                style: 'margin-bottom: 12px; padding: 8px; border: 1px solid #d9d9d9; border-radius: 4px;' 
              }, [
                h('div', { style: 'font-weight: bold; margin-bottom: 4px;' }, [
                  h('span', { style: 'color: #1890ff;' }, `第 ${index + 1} 条: `),
                  h('span', { style: result.success ? 'color: #52c41a;' : 'color: #ff4d4f;' }, 
                    result.success ? '✓ 成功' : '✗ 失败'
                  ),
                  h('span', { style: 'margin-left: 8px; color: #666;' }, 
                    `(${formatExecutionTime(result.executionTime)})`
                  )
                ]),
                h('div', { 
                  style: 'font-family: monospace; font-size: 12px; color: #666; margin-bottom: 4px; word-break: break-all;' 
                }, result.statement),
                result.success && result.affectedRows !== undefined && h('div', { style: 'color: #52c41a;' }, 
                  `影响行数: ${result.affectedRows}`
                ),
                !result.success && h('div', { style: 'color: #ff4d4f;' }, 
                  `错误: ${result.errorMessage}`
                )
              ])
            )
          ])
        ]),
        okText: '确定',
      });

      // 重新加载查询历史
      await loadQueryHistory();

    } catch (error) {
      message.error('批量执行SQL失败');
    } finally {
      executingMultiple.value = false;
      tableLoading.value = false;
    }
  };

  // 表格分页变化
  const handleTableChange = (pagination) => {
    currentPage.value = pagination.current;
    // 注意：这里不更新 pageSize.value，因为分页大小应该由布局控制面板统一管理
    // 表格的分页大小变化不应该影响查询设置中的分页大小
    if (isQueryMode.value) {
      executeSqlInternal();
    }
  };

  // 导出结果
  const handleExportResult = () => {
    if (!canExport.value) {
      message.warning('导出功能仅支持10000行以内的数据');
      return;
    }
    // TODO: 实现结果导出
    message.info('导出功能开发中');
  };

  // 清空历史
  const handleClearHistory = () => {
    Modal.confirm({
      title: '确认清空',
      content: '确定要清空所有查询历史记录吗？此操作不可恢复。',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
    queryHistory.value = [];
        message.success('查询历史已清空');
      },
    });
  };



  // 性能监控相关
  const handlePerformanceWarning = (warning) => {
    performanceWarnings.value.push(warning);
    showPerformanceMonitor.value = true;
  };

  const handlePerformanceSuggestion = (suggestion) => {
    performanceSuggestions.value.push(suggestion);
    showPerformanceMonitor.value = true;
  };

  // 格式化执行时间
  const formatExecutionTime = (milliseconds) => {
    if (milliseconds < 1000) {
      return `${milliseconds}ms`;
    }
    return `${(milliseconds / 1000).toFixed(2)}s`;
  };

  // 历史搜索
  const handleSearchHistory = () => {
    loadQueryHistory();
  };

  // 重用SQL
  const handleReuseSql = (record) => {
    sqlContent.value = record.sqlContent;
    currentPage.value = 1; // 重用时回到第一页
    // 重用SQL时使用当前查询设置的分页参数，确保一致性
    if (isQueryMode.value) {
      executeSqlInternal();
    }
  };



  // 键盘快捷键
  const handleKeyDown = (e) => {
    if (e.key === 'F5' && (e.ctrlKey || e.metaKey)) {
      e.preventDefault();
      handleExecuteSql();
    }
  };

  // 窗口大小变化处理
  const handleWindowResize = () => {
    // 确保控制面板在可视范围内
    const maxX = window.innerWidth - 320;
    const maxY = window.innerHeight - 400;
    
    if (controlPanelPosition.value.x > maxX) {
      controlPanelPosition.value.x = maxX;
    }
    if (controlPanelPosition.value.y > maxY) {
      controlPanelPosition.value.y = maxY;
    }
    
    // 确保控制按钮在可视范围内
    const maxButtonX = window.innerWidth - 40;
    const maxButtonY = window.innerHeight - 40;
    
    if (controlButtonPosition.value.x > maxButtonX) {
      controlButtonPosition.value.x = maxButtonX;
    }
    if (controlButtonPosition.value.y > maxButtonY) {
      controlButtonPosition.value.y = maxButtonY;
    }
    
    // 确保性能监控按钮在可视范围内
    if (performanceButtonPosition.value.x > maxButtonX) {
      performanceButtonPosition.value.x = maxButtonX;
    }
    if (performanceButtonPosition.value.y > maxButtonY) {
      performanceButtonPosition.value.y = maxButtonY;
    }
  };

  // 监听SQL编辑器行数变化 - 已移除，MonacoEditor自动处理
  // watch(sqlEditorRows, () => {
  //   updateLineNumbers();
  // });

  // 监听字体大小变化
  watch([sqlFontSize, lineNumberFontSize], () => {
    // 字体大小变化时不需要重新计算行号，只需要更新样式
    // nextTick(() => {
    //   updateSyntaxHighlight();
    // });
  });

  // 监听SQL内容变化，实时更新语法高亮
  watch(sqlContent, () => {
    // nextTick(() => {
    //   updateSyntaxHighlight();
    // });
  });

  // 监听查询结果变化，自动初始化列宽调整
  watch(queryResult, (newResult) => {
    if (newResult && newResult.success && newResult.columns && newResult.columns.length > 0) {
      // 使用多重延迟确保表格完全渲染
      nextTick(() => {
        setTimeout(() => {
          handleTableResize();
        }, 100);
      });
    }
  }, { deep: true });

  // 初始化
  onMounted(() => {
    getDatasourceList();
    document.addEventListener('keydown', handleKeyDown);
    window.addEventListener('resize', handleWindowResize);
    // updateLineNumbers(); // 初始化行号 - 已移除，MonacoEditor自动处理
    
    // 暂时禁用语法高亮
    // nextTick(() => {
    //   updateSyntaxHighlight();
    // });
  });

  // 加载查询历史
  const loadQueryHistory = async () => {
    if (!selectedDatasourceId.value) return;
    
    try {
      historyLoading.value = true;
      const res = await databaseManagerApi.getQueryHistory(selectedDatasourceId.value, {
        pageNum: 1,
        pageSize: 50,
        keyword: historySearchKeyword.value,
      });
      
      if (res.data && res.data.records) {
        queryHistory.value = res.data.records;
      }
    } catch (error) {
      message.error('加载查询历史失败');
    } finally {
      historyLoading.value = false;
    }
  };

  // 布局控制相关
  const toggleLayoutControls = () => {
    layoutControlsVisible.value = !layoutControlsVisible.value;
  };

  const resetLayout = () => {
    leftSiderWidth.value = 300;
    leftSiderCollapsed.value = false;
    leftSiderHidden.value = false;
    sqlEditorRows.value = 8;
    resultTableHeight.value = 400;
    historyTableHeight.value = 400;
    activeCollapseKeys.value = []; // 默认折叠所有面板
    pageSize.value = 50;
    maxRows.value = 1000;
    timeout.value = 30;
    sqlFontSize.value = 16;
    lineNumberFontSize.value = 14;
  };

  const handleLeftSiderCollapse = (collapsed) => {
    leftSiderCollapsed.value = collapsed;
  };

  const toggleLeftSider = () => {
    leftSiderCollapsed.value = !leftSiderCollapsed.value;
  };

  const toggleLeftSiderVisibility = () => {
    leftSiderHidden.value = !leftSiderHidden.value;
  };

  // 拖拽相关方法
  const startDrag = (e) => {
    if (e.target.closest('.ant-btn') || e.target.closest('.ant-slider') || e.target.closest('.ant-select')) {
      return; // 如果点击的是按钮、滑块或选择器，不开始拖拽
    }
    
    isDragging.value = true;
    const rect = e.currentTarget.getBoundingClientRect();
    dragOffset.value = {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top,
    };
    
    document.addEventListener('mousemove', handleDrag);
    document.addEventListener('mouseup', stopDrag);
    e.preventDefault();
  };

  const startDragButton = (e) => {
    isDraggingButton.value = true;
    const rect = e.currentTarget.getBoundingClientRect();
    dragOffset.value = {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top,
    };
    
    document.addEventListener('mousemove', handleDragButton);
    document.addEventListener('mouseup', stopDragButton);
    e.preventDefault();
  };

  const handleDrag = (e) => {
    if (!isDragging.value) return;
    
    const newX = e.clientX - dragOffset.value.x;
    const newY = e.clientY - dragOffset.value.y;
    
    // 边界检查
    const maxX = window.innerWidth - 320;
    const maxY = window.innerHeight - 400;
    
    controlPanelPosition.value = {
      x: Math.max(0, Math.min(newX, maxX)),
      y: Math.max(0, Math.min(newY, maxY)),
    };
  };

  const handleDragButton = (e) => {
    if (!isDraggingButton.value) return;
    
    const newX = e.clientX - dragOffset.value.x;
    const newY = e.clientY - dragOffset.value.y;
    
    // 边界检查
    const maxX = window.innerWidth - 40;
    const maxY = window.innerHeight - 40;
    
    controlButtonPosition.value = {
      x: Math.max(0, Math.min(newX, maxX)),
      y: Math.max(0, Math.min(newY, maxY)),
    };
  };

  const stopDrag = () => {
    isDragging.value = false;
    document.removeEventListener('mousemove', handleDrag);
    document.removeEventListener('mouseup', stopDrag);
  };

  const stopDragButton = () => {
    isDraggingButton.value = false;
    document.removeEventListener('mousemove', handleDragButton);
    document.removeEventListener('mouseup', stopDragButton);
  };

  // 性能监控按钮拖拽
  const startDragPerformanceButton = (e) => {
    isDraggingPerformanceButton.value = true;
    const rect = e.currentTarget.getBoundingClientRect();
    dragOffset.value = {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top,
    };
    
    document.addEventListener('mousemove', handleDragPerformanceButton);
    document.addEventListener('mouseup', stopDragPerformanceButton);
    e.preventDefault();
  };

  const handleDragPerformanceButton = (e) => {
    if (!isDraggingPerformanceButton.value) return;
    
    const newX = e.clientX - dragOffset.value.x;
    const newY = e.clientY - dragOffset.value.y;
    
    // 边界检查
    const maxX = window.innerWidth - 40;
    const maxY = window.innerHeight - 40;
    
    performanceButtonPosition.value = {
      x: Math.max(0, Math.min(newX, maxX)),
      y: Math.max(0, Math.min(newY, maxY)),
    };
  };

  const stopDragPerformanceButton = () => {
    isDraggingPerformanceButton.value = false;
    document.removeEventListener('mousemove', handleDragPerformanceButton);
    document.removeEventListener('mouseup', stopDragPerformanceButton);
  };

  // 按钮点击处理 - 防止拖拽时触发
  const handleLayoutButtonClick = () => {
    if (!isDraggingButton.value) {
      toggleLayoutControls();
    }
  };

  const handlePerformanceButtonClick = () => {
    if (!isDraggingPerformanceButton.value) {
      showPerformanceModal.value = true;
    }
  };

  // SQL输入处理 - 已移除，使用MonacoEditor的change事件
  // const handleSqlInput = () => {
  //   updateLineNumbers();
  // };

  // SQL键盘事件处理 - 已移除，MonacoEditor自带Tab键处理
  // const handleSqlKeyDown = (e) => {
  //   // 处理Tab键
  //   if (e.key === 'Tab') {
  //     e.preventDefault();
  //     const textarea = e.target;
  //     const start = textarea.selectionStart;
  //     const end = textarea.selectionEnd;
      
  //     // 插入制表符或空格
  //     const tabChar = '  '; // 使用两个空格代替Tab
  //     const newValue = textarea.value.substring(0, start) + tabChar + textarea.value.substring(end);
      
  //     // 更新值
  //     sqlContent.value = newValue;
      
  //     // 设置光标位置
  //     nextTick(() => {
  //         textarea.setSelectionRange(start + tabChar.length, start + tabChar.length);
  //     });
  //   }
  // };

  // 输入防抖定时器
  const inputTimeout = ref(null);

  // 行号相关方法 - 已移除，MonacoEditor自带行号
  // const updateLineNumbers = () => {
  //   const lines = sqlContent.value.split('\n');
  //   const maxLines = Math.max(lines.length, sqlEditorRows.value);
  //   lineNumbers.value = Array.from({ length: maxLines }, (_, i) => i + 1);
  // };

  // 滚动同步 - 已移除，MonacoEditor自带滚动处理
  // const syncScroll = () => {
  //   if (sqlTextareaRef.value && codeEditorRef.value) {
  //     const textarea = sqlTextareaRef.value.$el || sqlTextareaRef.value;
  //     const codeEditor = codeEditorRef.value;
  //     const lineNumbersContainer = textarea.parentElement.querySelector('.line-numbers');
      
  //     // 同步代码编辑器的滚动
  //     codeEditor.scrollTop = textarea.scrollTop;
  //     codeEditor.scrollLeft = textarea.scrollLeft;
      
  //     // 同步行号容器的滚动
  //     if (lineNumbersContainer) {
  //         lineNumbersContainer.scrollTop = textarea.scrollTop;
  //     }
  //   }
  // };

  // 暂时移除SQL语法高亮功能以避免布局冲突
  // const updateSyntaxHighlight = () => {
  //   // 语法高亮功能已暂时禁用
  // };

  // const highlightSQL = (sql) => {
  //   // 语法高亮功能已暂时禁用
  //   return sql;
  // };

  // 选中相关方法 - 已移除，使用MonacoEditor的select事件
  // const handleTextSelect = (e) => {
  //   const textarea = e.target;
  //   const start = textarea.selectionStart;
  //   const end = textarea.selectionEnd;
    
  //   selectionStart.value = start;
  //   selectionEnd.value = end;
  //   selectedText.value = textarea.value.substring(start, end);
    
  //   // 计算选中的行
  //   const lines = sqlContent.value.split('\n');
  //   let currentPos = 0;
  //   const selectedLineNumbers = [];
    
  //   lines.forEach((line, index) => {
  //     const lineStart = currentPos;
  //     const lineEnd = currentPos + line.length;
      
  //     if ((start >= lineStart && start <= lineEnd) || 
  //         (end >= lineStart && end <= lineEnd) ||
  //         (start <= lineStart && end >= lineEnd)) {
  //       selectedLineNumbers.push(index + 1);
  //     }
      
  //     currentPos += line.length + 1; // +1 for newline
  //   });
    
  //   selectedLines.value = selectedLineNumbers;
  // };

  // const isLineSelected = (lineNumber) => {
  //   return selectedLines.value.includes(lineNumber);
  // };

  // 暂时移除编辑器事件处理函数
  // const handleEditorClick = (e) => {
  //   // 点击代码编辑器时，将焦点转移到textarea
  //   if (sqlTextareaRef.value) {
  //     const textarea = sqlTextareaRef.value.$el || sqlTextareaRef.value;
  //     textarea.focus();
  //   }
  // };

  // const handleEditorKeyDown = (e) => {
  //   // 键盘事件转发到textarea
  //   if (sqlTextareaRef.value) {
  //     const textarea = sqlTextareaRef.value.$el || sqlTextareaRef.value;
  //     textarea.focus();
  //   }
  // };

  // 表格引用
  const resultTableRef = ref(null);

  // 列宽调整功能
  const handleTableResize = () => {
    if (!resultTableRef.value) return;
    
    const initResize = () => {
      const table = resultTableRef.value.$el;
      if (!table) return;
      
      const headers = table.querySelectorAll('.ant-table-thead th');
      if (headers.length === 0) {
        // 如果还没有表头，延迟重试
        setTimeout(initResize, 50);
        return;
      }
      
      headers.forEach((header, index) => {
        if (index === 0) return; // 跳过行号列
        
        // 设置表头为相对定位
        header.style.position = 'relative';
        
        // 创建调整手柄
        const resizeHandle = document.createElement('div');
        resizeHandle.className = 'resize-handle';
        resizeHandle.innerHTML = '&nbsp;';
        resizeHandle.style.cssText = `
          position: absolute;
          top: 0;
          right: -2px;
          width: 8px;
          height: 100%;
          background: rgba(24, 144, 255, 0.3);
          cursor: col-resize !important;
          z-index: 10;
          opacity: 0;
          transition: opacity 0.2s;
          border: 1px solid rgba(24, 144, 255, 0.5);
        `;
        
        header.appendChild(resizeHandle);
        
        // 鼠标悬停显示手柄
        header.addEventListener('mouseenter', () => {
          resizeHandle.style.opacity = '1';
        });
        
        header.addEventListener('mouseleave', () => {
          resizeHandle.style.opacity = '0';
        });
        
        // 直接在resizeHandle上绑定事件
        let isResizing = false;
        let startX = 0;
        let startWidth = 0;
        
        resizeHandle.onmousedown = function(e) {
          e.preventDefault();
          e.stopPropagation();
          
          isResizing = true;
          startX = e.clientX;
          startWidth = header.offsetWidth;
          
          // 添加调整中的样式
          header.classList.add('resizing');
          resizeHandle.style.opacity = '1';
          resizeHandle.style.background = 'rgba(24, 144, 255, 0.6)';
          
          document.onmousemove = function(e) {
            if (!isResizing) return;
            
            const deltaX = e.clientX - startX;
            const newWidth = startWidth + deltaX;
            
            // 设置合理的宽度范围：最小50px，最大500px
            const finalWidth = Math.max(50, Math.min(newWidth, 500));
            
            // 更新表头宽度
            header.style.width = finalWidth + 'px';
            header.style.minWidth = finalWidth + 'px';
            
            // 更新对应的表格单元格宽度
            const table = resultTableRef.value.$el;
            if (table) {
              // 更新表头单元格
              const headerCells = table.querySelectorAll(`.ant-table-thead th:nth-child(${index + 1})`);
              headerCells.forEach(cell => {
                cell.style.width = finalWidth + 'px';
                cell.style.minWidth = finalWidth + 'px';
              });
              
              // 更新数据单元格
              const dataCells = table.querySelectorAll(`.ant-table-tbody td:nth-child(${index + 1})`);
              dataCells.forEach(cell => {
                cell.style.width = finalWidth + 'px';
                cell.style.minWidth = finalWidth + 'px';
              });
              
              // 强制表格重新计算布局
              table.style.tableLayout = 'fixed';
            }
            
            // 更新对应的数据列宽度
            const columnKey = queryResult.value?.columns?.[index - 1]?.name;
            if (columnKey) {
              columnWidths.value[columnKey] = finalWidth;
              // 强制触发响应式更新
              columnWidths.value = { ...columnWidths.value };
            }
          };
          
          document.onmouseup = function() {
            isResizing = false;
            header.classList.remove('resizing');
            resizeHandle.style.background = 'rgba(24, 144, 255, 0.3)';
            
            document.onmousemove = null;
            document.onmouseup = null;
            
            document.body.style.cursor = '';
            document.body.style.userSelect = '';
          };
          
          document.body.style.cursor = 'col-resize';
          document.body.style.userSelect = 'none';
        };
      });
    };
    
    // 开始初始化
    initResize();
  };

  // 清理
  onUnmounted(() => {
    document.removeEventListener('keydown', handleKeyDown);
    document.removeEventListener('mousemove', handleDrag);
    document.removeEventListener('mouseup', stopDrag);
    document.removeEventListener('mousemove', handleDragButton);
    document.removeEventListener('mouseup', stopDragButton);
    document.removeEventListener('mousemove', handleDragPerformanceButton);
    document.removeEventListener('mouseup', stopDragPerformanceButton);

    window.removeEventListener('resize', handleWindowResize);
    
    // 清理输入防抖定时器
    if (inputTimeout.value) {
      clearTimeout(inputTimeout.value);
    }
  });

  // 选区处理
  function handleMonacoSelect(val) {
    selectedText.value = val;
  }

  // 内容变更处理
  function handleMonacoChange(val) {
    // MonacoEditor内容变更时的处理
    // 可以在这里添加额外的逻辑，如自动保存等
  }
</script>

<style scoped>
  .database-manager {
    height: 100vh;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }

  /* 左侧数据源面板 */
  .datasource-sider {
    background: #fff !important;
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
    border-right: 1px solid #e8e8e8;
    position: relative;
  }

  .datasource-sider.ant-layout-sider-collapsed {
    background: linear-gradient(180deg, #f8f9fa 0%, #e9ecef 100%) !important;
  }

  .sider-content {
    padding: 20px;
    height: 100%;
    overflow-y: auto;
    position: relative;
  }

  .datasource-sider.ant-layout-sider-collapsed .sider-content {
    padding: 0;
  }

  .sider-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;
  }

  .header-title {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .header-icon {
    color: #1890ff;
    font-size: 18px;
  }

  .sider-header h3 {
    margin: 0;
    color: #262626;
    font-weight: 600;
    font-size: 16px;
  }

  .refresh-btn {
    color: #666;
    transition: all 0.3s;
  }

  .refresh-btn:hover {
    color: #1890ff;
    transform: rotate(180deg);
  }

  /* 数据源选择器 */
  .datasource-selector {
    margin-bottom: 24px;
  }

  .selector-label {
    display: block;
    margin-bottom: 8px;
    color: #595959;
    font-weight: 500;
    font-size: 14px;
  }

  .datasource-select {
    width: 100%;
  }

  .datasource-option {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .option-icon {
    color: #1890ff;
  }

  /* 数据库对象树 */
  .object-tree-container {
    margin-top: 16px;
  }

  .tree-label {
    display: block;
    margin-bottom: 12px;
    color: #595959;
    font-weight: 500;
    font-size: 14px;
  }

  .object-tree {
    background: #fafafa;
    border-radius: 6px;
    padding: 8px;
  }

  .tree-node {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 4px 0;
  }

  .tree-icon {
    font-size: 14px;
  }

  .database-icon {
    color: #1890ff;
  }

  .table-icon {
    color: #52c41a;
  }

  .view-icon {
    color: #fa8c16;
  }

  .node-title {
    color: #262626;
    font-size: 14px;
  }

  /* 侧边栏触发器 */
  .sider-trigger {
    position: absolute;
    top: 50%;
    right: -16px;
    transform: translateY(-50%);
    width: 16px;
    height: 32px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 0 4px 4px 0;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: white;
    font-size: 12px;
    transition: all 0.3s;
    z-index: 10;
    box-shadow: 2px 0 4px rgba(0, 0, 0, 0.1);
  }

  .sider-trigger:hover {
    background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
    transform: translateY(-50%) scale(1.05);
  }

  /* 折叠时的数据源列表 */
  .collapsed-datasource-list {
    padding: 16px 8px;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .collapsed-header {
    margin-bottom: 16px;
    padding: 8px;
    background: rgba(24, 144, 255, 0.1);
    border-radius: 6px;
    color: #1890ff;
  }

  .collapsed-icon {
    font-size: 16px;
  }

  .collapsed-datasources {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 8px;
    width: 100%;
  }

  .collapsed-datasource-item {
    width: 32px;
    height: 32px;
    border-radius: 6px;
    background: #f5f5f5;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;
    border: 2px solid transparent;
  }

  .collapsed-datasource-item:hover {
    background: #e6f7ff;
    border-color: #91d5ff;
  }

  .collapsed-datasource-item.active {
    background: #1890ff;
    color: white;
    border-color: #1890ff;
  }

  .collapsed-datasource-item .item-icon {
    font-size: 14px;
  }

  .collapsed-more {
    margin-top: 8px;
    padding: 8px;
    color: #999;
    cursor: pointer;
    transition: color 0.3s;
  }

  .collapsed-more:hover {
    color: #1890ff;
  }

  /* 主要内容区域 */
  .main-content {
    padding: 20px;
    background: #f5f7fa;
  }

  .content-wrapper {
    height: 100%;
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .sql-editor-section {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    overflow: hidden;
  }

  .editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
  }

  .header-left {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .header-left h3 {
    margin: 0;
    font-weight: 600;
    font-size: 16px;
  }

  .toggle-sider-btn {
    margin-left: 16px;
    color: rgba(255, 255, 255, 0.8);
    border: 1px solid rgba(255, 255, 255, 0.2);
    background: rgba(255, 255, 255, 0.1);
    transition: all 0.3s;
    font-size: 12px;
    height: 28px;
    padding: 0 12px;
  }

  .toggle-sider-btn:hover {
    color: white;
    background: rgba(255, 255, 255, 0.2);
    border-color: rgba(255, 255, 255, 0.4);
  }

  .header-actions {
    display: flex !important;
    gap: 8px;
    align-items: center;
    flex-shrink: 0;
  }

  .action-btn {
    background: rgba(255, 255, 255, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.3);
    color: white;
    transition: all 0.3s;
  }

  .action-btn:hover {
    background: rgba(255, 255, 255, 0.3);
    border-color: rgba(255, 255, 255, 0.5);
    color: white;
  }

  .execute-btn {
    background: linear-gradient(135deg, #52c41a 0%, #389e0d 100%) !important;
    border-color: #52c41a !important;
    color: white !important;
    font-weight: 600;
    display: inline-flex !important;
    align-items: center;
    gap: 6px;
    min-width: 90px;
    justify-content: center;
    box-shadow: 0 2px 8px rgba(82, 196, 26, 0.3);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
  }

  .execute-btn::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: left 0.5s;
  }

  .execute-btn:hover {
    background: linear-gradient(135deg, #73d13d 0%, #52c41a 100%) !important;
    border-color: #73d13d !important;
    color: white !important;
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(82, 196, 26, 0.4);
  }

  .execute-btn:hover::before {
    left: 100%;
  }

  .execute-btn:focus {
    background: linear-gradient(135deg, #52c41a 0%, #389e0d 100%) !important;
    border-color: #52c41a !important;
    color: white !important;
    box-shadow: 0 0 0 2px rgba(82, 196, 26, 0.2);
  }

  .execute-btn:active {
    transform: translateY(0);
    box-shadow: 0 2px 4px rgba(82, 196, 26, 0.3);
  }

  .execute-multiple-btn {
    background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%) !important;
    border-color: #ff6b6b !important;
    color: white !important;
    font-weight: 600;
    display: inline-flex !important;
    align-items: center;
    gap: 6px;
    min-width: 90px;
    justify-content: center;
    box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
  }

  .execute-multiple-btn::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: left 0.5s;
  }

  .execute-multiple-btn:hover {
    background: linear-gradient(135deg, #ff5252 0%, #d63031 100%) !important;
    border-color: #ff5252 !important;
    color: white !important;
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(255, 107, 107, 0.4);
  }

  .execute-multiple-btn:hover::before {
    left: 100%;
  }

  .execute-multiple-btn:focus {
    background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%) !important;
    border-color: #ff6b6b !important;
    color: white !important;
    box-shadow: 0 0 0 2px rgba(255, 107, 107, 0.2);
  }

  .execute-multiple-btn:active {
    transform: translateY(0);
    box-shadow: 0 2px 4px rgba(255, 107, 107, 0.3);
  }

  .execute-multiple-btn:disabled {
    background: linear-gradient(135deg, #f5f5f5 0%, #e8e8e8 100%) !important;
    border-color: #d9d9d9 !important;
    color: #bfbfbf !important;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
  }

  .execute-multiple-btn:disabled::before {
    display: none;
  }

  .editor-container {
    border: none;
    border-radius: 0;
  }

  .sql-editor-wrapper {
    display: flex;
    position: relative;
    background: #ffffff;
    border-radius: 0 0 12px 12px;
    border: 1px solid #e8e8e8;
  }

  /* 移除自定义行号样式，MonacoEditor自带行号 */
  /* .line-numbers {
    width: 60px;
    background: #f8f9fa;
    border-right: 1px solid #e8e8e8;
    padding: 12px 0;
    text-align: right;
    font-family: 'Courier New', monospace;
    color: #666666;
    user-select: none;
    overflow: hidden;
  }

  .line-number {
    padding: 0 12px;
    line-height: 1.8;
  } */

  /* 移除textarea样式，使用MonacoEditor */
  /* .sql-textarea {
    flex: 1;
    font-family: 'Courier New', monospace !important;
    background: #ffffff !important;
    color: #333333 !important;
    border: none !important;
    border-radius: 0 !important;
    resize: none;
    padding: 12px 16px !important;
    line-height: 1.8;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow-wrap: break-word;
    overflow-x: auto;
    overflow-y: auto;
    font-size: inherit;
    letter-spacing: normal;
    word-spacing: normal;
    box-sizing: border-box;
    position: relative;
    z-index: 0;
    font-weight: normal;
    tab-size: 2;
    -moz-tab-size: 2;
    -o-tab-size: 2;
    -webkit-tab-size: 2;
  }

  .sql-textarea:focus {
    box-shadow: none !important;
    outline: none !important;
  }

  .sql-textarea::placeholder {
    color: #999999 !important;
  } */

  /* 代码编辑器容器 - 已移除，使用MonacoEditor */
  /* .code-editor-container {
    position: relative;
    flex: 1;
  } */

  /* 移除语法高亮层样式，避免布局冲突 */

  /* 确保textarea的样式与pre完全一致 */
  /* 移除重复的sql-textarea样式定义，使用之前定义的版本 */

  /* SQL语法高亮样式 */
  .sql-keyword {
    color: #1890ff !important;
    font-weight: bold;
  }

  .sql-string {
    color: #f5222d !important;
  }

  .sql-number {
    color: #52c41a !important;
  }

  .sql-comment {
    color: #8c8c8c !important;
    font-style: italic;
  }

  .sql-identifier {
    color: #722ed1 !important;
  }

  /* 选中行高亮 */
  .selected-line {
    background: rgba(24, 144, 255, 0.1);
    color: #1890ff !important;
    font-weight: bold;
  }

  /* .line-numbers .selected-line {
    background: rgba(24, 144, 255, 0.2);
    color: #1890ff !important;
  } */

  /* 可折叠区域 */
  .collapsible-sections {
    flex: 1;
    overflow-y: auto;
  }

  .custom-collapse {
    background: transparent;
  }

  .custom-collapse :deep(.ant-collapse-item) {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    margin-bottom: 16px;
    border: none;
    overflow: hidden;
  }

  .custom-collapse :deep(.ant-collapse-header) {
    background: linear-gradient(135deg, #f0f2f5 0%, #e6f7ff 100%);
    padding: 16px 20px !important;
    border-bottom: 1px solid #f0f0f0;
  }

  .custom-collapse :deep(.ant-collapse-content) {
    border: none;
  }

  .custom-collapse :deep(.ant-collapse-content-box) {
    padding: 20px;
  }

  .panel-header {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    color: #262626;
  }

  .panel-icon {
    color: #1890ff;
    font-size: 16px;
  }

  .result-panel :deep(.ant-collapse-header) {
    background: linear-gradient(135deg, #f6ffed 0%, #e6f7ff 100%);
  }

  .history-panel :deep(.ant-collapse-header) {
    background: linear-gradient(135deg, #fff7e6 0%, #e6f7ff 100%);
  }



  .collapsible-sections {
    flex: 1;
    overflow-y: auto;
  }

  .result-section {
    margin-bottom: 16px;
  }

  .result-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }

  .result-header h3 {
    margin: 0;
  }

  .error-message {
    margin-bottom: 16px;
  }

  .result-table {
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    overflow: hidden;
  }

  /* 行号列样式 */
  .result-table :deep(.ant-table-thead > tr > th:first-child) {
    background: #fafafa;
    border-right: 1px solid #f0f0f0;
    font-weight: 600;
    color: #262626;
    width: 40px !important;
    min-width: 40px !important;
    max-width: 40px !important;
  }

  .result-table :deep(.ant-table-tbody > tr > td:first-child) {
    background: #fafafa;
    border-right: 1px solid #f0f0f0;
    text-align: center;
    font-weight: 500;
    width: 40px !important;
    min-width: 40px !important;
    max-width: 40px !important;
  }

  .result-table :deep(.ant-table-tbody > tr:hover > td:first-child) {
    background: #e6f7ff;
  }

  /* 数据单元格样式 - 处理长内容 */
  .result-table :deep(.ant-table-tbody > tr > td) {
    word-break: break-word;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .result-table :deep(.ant-table-tbody > tr > td:first-child) {
    white-space: nowrap;
    overflow: visible;
  }

  /* 列宽调整样式 */
  .result-table :deep(.ant-table-thead > tr > th) {
    position: relative;
  }

  .result-table :deep(.ant-table-thead > tr > th:first-child) {
    cursor: default;
  }

  .column-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 100%;
  }

  .resize-handle {
    position: absolute;
    top: 0;
    right: -2px;
    width: 8px;
    height: 100%;
    background: rgba(24, 144, 255, 0.3);
    cursor: col-resize !important;
    z-index: 10;
    opacity: 0;
    transition: opacity 0.2s, background-color 0.2s;
    pointer-events: auto !important;
  }

  .resize-handle:hover {
    background: rgba(24, 144, 255, 0.5);
    opacity: 1;
  }

  .result-table :deep(.ant-table-thead > tr > th) {
    position: relative;
  }

  .result-table :deep(.ant-table-thead > tr > th.resizing) {
    background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%) !important;
  }

  .result-table :deep(.ant-table-thead > tr > th) .resize-handle {
    z-index: 10;
  }

  .success-message {
    margin-bottom: 16px;
  }

  .history-section {
    flex: 1;
  }

  .history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }

  .history-header h3 {
    margin: 0;
  }

  .history-item {
    width: 100%;
  }

  .history-sql {
    font-family: 'Courier New', monospace;
    font-size: 12px;
    color: #666;
    margin-bottom: 4px;
    word-break: break-all;
  }

  .history-info {
    display: flex;
    gap: 8px;
    font-size: 12px;
    color: #999;
  }

  .sql-content {
    font-family: 'Courier New', monospace;
    font-size: 12px;
    color: #666;
    word-break: break-all;
  }

  /* 布局控制面板 */
  .layout-controls {
    position: fixed;
    z-index: 1000;
    user-select: none;
  }

  .control-card {
    width: 320px;
    cursor: move;
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
    border: 1px solid rgba(255, 255, 255, 0.2);
    backdrop-filter: blur(10px);
  }

  .control-card :deep(.ant-card-head) {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 12px 12px 0 0;
    padding: 12px 16px;
  }

  .control-card :deep(.ant-card-body) {
    max-height: 70vh;
    overflow-y: auto;
    background: rgba(255, 255, 255, 0.95);
  }

  .card-title {
    display: flex;
    align-items: center;
    gap: 8px;
    color: white;
    font-weight: 600;
  }

  .title-icon {
    font-size: 16px;
  }

  .control-btn {
    color: white;
    border: 1px solid rgba(255, 255, 255, 0.3);
    background: rgba(255, 255, 255, 0.1);
    transition: all 0.3s;
  }

  .control-btn:hover {
    background: rgba(255, 255, 255, 0.2);
    border-color: rgba(255, 255, 255, 0.5);
    color: white;
  }

  /* 悬浮按钮 */
  .show-controls-btn {
    position: fixed;
    z-index: 1000;
    user-select: none;
  }

  .show-controls-btn .ant-btn {
    box-shadow: 0 4px 16px rgba(24, 144, 255, 0.3);
    border-radius: 50%;
    width: 48px;
    height: 48px;
    transition: all 0.3s;
  }

  .show-controls-btn .ant-btn:hover {
    transform: scale(1.1);
    box-shadow: 0 6px 20px rgba(24, 144, 255, 0.4);
  }

  .performance-monitor-btn {
    position: fixed;
    z-index: 1000;
    user-select: none;
  }

  .performance-monitor-btn .ant-btn {
    box-shadow: 0 4px 16px rgba(82, 196, 26, 0.3);
    border-radius: 50%;
    width: 48px;
    height: 48px;
    transition: all 0.3s;
  }

  .performance-monitor-btn .ant-btn:hover {
    background: #73d13d !important;
    border-color: #73d13d !important;
    transform: scale(1.1);
    box-shadow: 0 6px 20px rgba(82, 196, 26, 0.4);
  }

  /* 显示左侧面板的浮动按钮 */
  .show-sider-btn {
    position: fixed;
    z-index: 1000;
    user-select: none;
  }

  .show-sider-btn .ant-btn {
    box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
    border-radius: 50%;
    width: 48px;
    height: 48px;
    transition: all 0.3s;
  }

  .show-sider-btn .ant-btn:hover {
    transform: scale(1.1);
    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .main-content {
      padding: 12px;
    }
    
    .sider-content {
      padding: 16px;
    }
    
    .control-card {
      width: 280px;
    }
  }
</style> 